package com.tledu.stu_manager.filter;

import com.tledu.stu_manager.constant.SessionConstant;
import com.tledu.stu_manager.model.Student;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 登录过滤器
 *
 * @author Antg
 * @date 2021/7/3115:36
 */
@WebFilter("/*")
public class LoginFilter extends HttpFilter {
    private List<String> skipList = Arrays.asList("/login.jsp", "/login");

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        String servletPath = req.getServletPath();
        if (skipList.contains(servletPath)) {
            chain.doFilter(req, res);
            return;
        }
        //不过滤静态资源
        if (servletPath.startsWith("/resources")) {
            chain.doFilter(req, res);
            return;
        }

        Student student = (Student) req.getSession().getAttribute(SessionConstant.CURRENT_LOGIN_USER);
        if (student == null) {
            res.sendRedirect(req.getContextPath() + "/login.jsp");
            return;
        }
        chain.doFilter(req, res);
    }
}
